package org.geektimes.projects.user.web.controller;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.Path;

import org.apache.commons.collections.CollectionUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;

@Path("/")
public class UserController implements PageController {
	
	@Resource(name = "bean/UserService")
	private UserService userService;
	
	@Resource(name = "bean/Validator")
	private Validator validator;
	
	@Path("/register")
	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		String method = request.getMethod();
		if ("GET".equalsIgnoreCase(method)) {
			return "register.jsp";
		} else {
			User user = new User();
			user.setName(request.getParameter("name"));
			user.setPhoneNumber(request.getParameter("phone"));
			user.setEmail(request.getParameter("email"));
			user.setPassword(request.getParameter("password"));
			boolean result = false;
			Set<ConstraintViolation<User>> constraintViolations =  validator.validate(user);
			String error = "";
			if( !CollectionUtils.isEmpty(constraintViolations) ){
				error = constraintViolations.iterator().next().getMessage();
			}else {
				result = userService.register(user);
			}
			
			return "result.jsp?result=" + result + "&error=" + error;

		}

	}

}
